// @flow
import React, { Component } from 'react'
import { Modal, Form, Input, message, Select, Upload, Icon, Button } from 'antd'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
import styles from './DeviceTypeInfoEdit.css'
const FormItem = Form.Item
import R from 'ramda'
const Option = Select.Option
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 }
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 14 }
  }
}
type Props = {
  visible: boolean,
  deviceId: string,
  data: Object,
  closeModal: Function,
  form: Object
}

type States = {
  confirmLoading: boolean,
  deviceComponents: Array<Object>,
  imageUrl: string,
  remoteImageUrl: string,
  pointData: Array<any>
}
class DeviceTypeInfoEdit extends Component {
  props: Props
  state: States
  editDeviceType: Function
  changeFile: Function
  getPointData: Function
  beforeUpload: Function
  constructor (props: Props) {
    super(props)
    this.state = {
      confirmLoading: false,
      deviceComponents: [],
      imageUrl: '',
      pointData: [],
      remoteImageUrl: ''
    }
    this.editDeviceType = this.editDeviceType.bind(this)
    this.changeFile = this.changeFile.bind(this)
    this.getPointData = this.getPointData.bind(this)
    this.beforeUpload = this.beforeUpload.bind(this)
  }
  getPointData () {
    universalFetch(`${__SERVICE_API__}device/templates/monitors/points`)
    .then((res) => res.json())
    .then((json) => {
      if (json.code !== 200000) {
        throw new Error(JSON.stringify({ code: json.code, message: json.message }))
      }
      this.setState({
        pointData: json.result
      })
      // pointData = json.result
    })
    .catch((error) => {
      handleFetchError(error)
      console.error(error)
    })
  }

  changeFile (info) {
    const response = info.file.response
    if (response && response.code === 200000) {
      this.setState({
        imageUrl: response.result.name,
        remoteImageUrl: response.result.url
      })
    }
  }

  beforeUpload (file) {
    const type = file.type.toLocaleLowerCase()
    if (type.indexOf('image/') === -1) {
      message.error('只能上传图片', 3)
    }
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isLt2M) {
      message.error('图片必须小于2MB!')
    }
    return type.indexOf('image/') > -1
  }

  editDeviceType () {
    const { form, data, deviceId, closeModal } = this.props
    form.validateFields((err, fieldsValue) => {
      if (err) {
        return false
      }
      this.setState({
        confirmLoading: true
      })
      const { imageUrl } = this.state
      let values
      if (data.parentId !== 0) {
        values = {
          ...fieldsValue,
          neqIsUploadKmx: data.neqIsUploadKmx
        }
      } else {
        values = {
          ...Object.assign({}, fieldsValue, { imageUrl }),
          neqIsUploadKmx: data.neqIsUploadKmx,
          parentId: data.parentId
        }
      }
      universalFetch(`${__SERVICE_API__}device/templates/devices/${deviceId}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        },
        body: JSON.stringify(values)
      })
        .then(res => res.json())
        .then((json) => {
          if (json.code !== 200000) {
            throw new Error(JSON.stringify({ code: json.code, message: json.message }))
          }
          message.success('设备模板修改成功')
          this.setState({
            confirmLoading: false
          })
          closeModal()
        })
        .catch((error) => {
          this.setState({
            confirmLoading: false
          })
          handleFetchError(error)
          console.error(error)
        })
    })
  }

  componentWillMount () {
    const { data } = this.props
    let imageUrl = data.imageUrl
    if (!imageUrl) return
    const index = imageUrl.lastIndexOf('/')
    imageUrl = imageUrl.substring(index + 1, imageUrl.length)
    this.setState({
      imageUrl: imageUrl,
      remoteImageUrl: data.imageUrl
    })
  }

  componentDidMount () {
    this.getRootDeviceTypes()
    this.getPointData()
  }

  getDeviceTypes (data, map) {
    const { deviceId } = this.props
    data.map((item) => {
      if (item.id !== deviceId && item.parentId !== deviceId) {
        if (item.children && item.children.length > 0) {
          map.push(R.omit(['children'], item))
          this.getDeviceTypes(item.children, map)
        } else {
          map.push(R.omit(['children'], item))
        }
      }
    })
  }
  getRootDeviceTypes () {
    const { deviceId } = this.props
    universalFetch(`${__SERVICE_API__}device/templates/devices?id=${deviceId}&type=deep&isComponent=1`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        const results = json.result
        const deviceComponents = []
        results.map((item) => {
          if (item.children && item.children.length > 0) {
            deviceComponents.push(R.omit(['children'], item))
            this.getDeviceTypes(item.children, deviceComponents)
          } else {
            deviceComponents.push(R.omit('children', item))
          }
        })
        this.setState({
          deviceComponents: deviceComponents
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  render () {
    const { getFieldDecorator } = this.props.form
    const { visible, closeModal, data } = this.props
    const { confirmLoading, deviceComponents, remoteImageUrl, pointData } = this.state
    const token = localStorage.getItem('asset_token')
    const pointChildren = pointData.map((d, i) => {
      return <Option key={i} value={d.id}>{d.sensorName}</Option>
    })
    return (
      <Modal
        title='编辑设备模板'
        visible={visible}
        onCancel={closeModal}
        onOk={this.editDeviceType}
        maskClosable={false}
        confirmLoading={confirmLoading}
        >
        <Form>
          <FormItem {...formItemLayout} label='名称'>
            {
              getFieldDecorator('name', {
                rules: [
                  { required: true, message: '请输入名称', whitespace: true }
                ],
                initialValue: data.name
              })(
                <Input placeholder='请输入名称' ref={(e) => {
                  e.refs.input.focus()
                }} />
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label='类型'>
            {
              getFieldDecorator('type', {
                initialValue: data.type
              })(
                <Input placeholder='请输入类型' disabled />
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label='型号'>
            {
              getFieldDecorator('spec', {
                initialValue: data.spec
              })(
                <Input placeholder='请输入型号' disabled />
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label='测点' hasFeedback>
            {getFieldDecorator('monitorPointIds', {})(
              <Select showSearch mode='multiple'
                filterOption={(input, option) => {
                  return option.props.children.indexOf(input) >= 0
                }}
                placeholder='请选择测点'
                >
                {pointChildren}
              </Select>
            )}
          </FormItem>
          {
            data.parentId !== 0
            ? <FormItem {...formItemLayout} label='父级组件'>
              {
                getFieldDecorator('parentId', {
                  initialValue: `${data.parentId}`
                })(
                  <Select showSearch
                    filterOption={(input, option) => {
                      return option.props.children.indexOf(input) >= 0
                    }} placeholder='请选择父级组件'>
                    {
                      deviceComponents.map((item, i) => {
                        return <Option key={i} value={`${item.id}`}>
                          {item.name}
                        </Option>
                      })
                    }
                  </Select>
                )
              }
            </FormItem>
            : false
          }
          {
            data.imageUrl
            ? <FormItem {...formItemLayout} label='设备模板图片'>
              {
                getFieldDecorator('imageUrl', {})(
                  <Upload
                    {...{
                      name: 'file',
                      className: styles['avatar-uploader'],
                      action: `${__SERVICE_API__}static/statics`,
                      headers:{ 'X-Auth':token },
                      onChange: this.changeFile,
                      beforeUpload: this.beforeUpload,
                      showUploadList: false
                    }}
                    >
                    {
                      remoteImageUrl
                      ? <div className={styles['image-preview']}>
                        <img src={remoteImageUrl} style={{ width: '100%' }} />
                        <div className={styles['over-avatar']}>
                          更换图片
                        </div>
                      </div>
                      : <Button style={{ width: '150px' }}>
                        <Icon type='upload' />上传图片
                      </Button>
                    }
                  </Upload>
                )
              }
            </FormItem>
            : false
          }
          <FormItem {...formItemLayout} label='备注'>
            {
              getFieldDecorator('remark', {
                initialValue: data.remark
              })(
                <Input placeholder='请输入备注' type='textarea'
                  autosize={{ minRows: 2 }}
                  />
              )
            }
          </FormItem>
        </Form>
      </Modal>
    )
  }
}

export default Form.create()(DeviceTypeInfoEdit)
